﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Validation.Configuration;

namespace BaMusaSoft.RPS.RPSServices
{
    [ConfigurationElementType(typeof(CustomValidatorData))]
    public class DateValidator : Validator<string>
    {
        public DateValidator(string template, string tag):base(template, tag)
        {
           
        }
        public DateValidator(NameValueCollection attributes) : base(string.Empty, string.Empty)
        {
      
            
        }

        protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            bool isValid = IsValidDate(objectToValidate);
            if (!isValid)
            {
                LogValidationResult(validationResults, GetMessage(objectToValidate, key), currentTarget, key);
            }
           
        }

        protected override string DefaultMessageTemplate
        {
            get { throw new NotImplementedException(); }
        }

        private bool IsValidDate(string dateString)
        {
            bool result = false;
            if (string.IsNullOrEmpty(dateString)) { return false; }
            if (dateString.Length != 8) { return false; }
            string d = dateString.Substring(6, 2);
            string m = dateString.Substring(4, 2);
            string y = dateString.Substring(0, 4);

            int day;
            int month;
            int year;

            if (int.TryParse(d, out day) &&
                int.TryParse(m, out month) &&
                int.TryParse(y, out year))
            {
                if (
                     (day > 0 && day < 31)
                     &&
                     (month > 0 && month <= 12)
                     &&
                     (year > 1400))
                {
                    result = true;
                }
            }
            return result;
        }
    }
}
